/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.kits.asyn;

import com.google.common.collect.Maps;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Map;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-05-19 21:37
 * @since JDK 1.6
 */
public class ImportMemberThread {

    public static final ImportMemberThread        instace     = new ImportMemberThread();
    private final       Map<String, ImportThread> file_import = Maps.newHashMap();

    private ImportMemberThread() {
    }

    public static ImportMemberThread getInstace() {
        return instace;
    }

    /**
     * @return 0 正在运行
     * -1 只能同时导入3个文件
     * 1 正在导入
     */
    public int start(File file) {
        if (file_import.size() > 3) {
            return -1;
        }
        String name = Files.getNameWithoutExtension(file.getName());
        if (file_import.containsKey(name)) {
            ImportThread thread = file_import.get(name);
            if (thread.isRunning()) {
                return 0;
            }
        } else {

            ImportThread thread = new ImportThread(file);
            thread.start();
            file_import.put(name, thread);
        }
        return 1;
    }

    public void stop(File file) {
        String name = Files.getNameWithoutExtension(file.getName());
        if (file_import.containsKey(name)) {
            ImportThread thread = file_import.get(name);
            if (thread.isRunning()) {
                thread.interrupt();
            }
        }
    }

    public class ImportThread extends Thread {
        private final File file;
        private volatile boolean running = true;

        public ImportThread(File file) {
            this.file = file;
            setDaemon(true);
        }

        @Override
        public void run() {
            while (running) {
                String extension = Files.getFileExtension(file.getName());
                if (StringUtils.equals("xls", extension) || StringUtils.equals("xlsx", extension)) {
                    MemberImportKit.import_excel(file);
                } else if (StringUtils.equals("tsv", extension)) {
                    MemberImportKit.import_tsv(file);
                }
                // 删除上传的文件
                FileUtils.deleteQuietly(file);
                running = false;
            }
        }

        public boolean isRunning() {
            return running;
        }
    }


}
